using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;

namespace Magiq.Sql {
    public class ColumnProvider<T> where T : class
    {
        private readonly DataContext dataContext;

        private IEnumerable<MetaDataMember> persistentDataMembers;
        public ColumnProvider(DataContext dataContext)
        {
            this.dataContext = dataContext;
        }

        private IEnumerable<MetaDataMember> PersistentDataMembers
        {
            get
            {
                if (persistentDataMembers == null)
                    persistentDataMembers = dataContext.Mapping
                        .MappingSource
                        .GetModel(typeof(T))
                        .GetTable(typeof(T))
                        .RowType
                        .PersistentDataMembers;

                return persistentDataMembers;
            }
        }
        public string ColumnFor(string propertyName)
        {
            return PersistentDataMembers.Single(m => m.Member.Name == propertyName).MappedName;
        }
    }
}